﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace DemoV5
{
    public static class SocketExtensions
    {
        public static SocketAwaitable ReceiveAsync(this Socket socket,
            SocketAwaitable awaitable)
        {
            awaitable.Reset();
            if (!socket.ReceiveAsync(awaitable.m_eventArgs))
                awaitable.m_wasCompleted = true;
            return awaitable;
        }

        public static SocketAwaitable SendAsync(this Socket socket,
            SocketAwaitable awaitable)
        {
            awaitable.Reset();
            if (!socket.SendAsync(awaitable.m_eventArgs))
                awaitable.m_wasCompleted = true;
            return awaitable;
        }
        //static async Task ReadAsync(Socket s)
        //{
        //    // Reusable SocketAsyncEventArgs and awaitable wrapper 
        //    var args = new SocketAsyncEventArgs();
        //    args.SetBuffer(new byte[0x1000], 0, 0x1000);
        //    var awaitable = new ReceiveSocketAwaitable(args);

        //    // Do processing, continually receiving from the socket 
        //    int bytesRead;
        //    while ((bytesRead = await s.ReceiveAsync(awaitable)) > 0)
        //    {
        //        Console.WriteLine(bytesRead);
        //    }
        //}
        //static async Task ReadAsync(Socket s)
        //{
        //    // Reusable SocketAsyncEventArgs and awaitable wrapper 
        //    var args = new SocketAsyncEventArgs();
        //    args.SetBuffer(new byte[0x1000], 0, 0x1000);
        //    var awaitable = new SocketAwaitable(args);

        //    // Do processing, continually receiving from the socket 
        //    while (true)
        //    {
        //        await s.ReceiveAsync(awaitable);
        //        int bytesRead = args.BytesTransferred;
        //        if (bytesRead <= 0) break;

        //        Console.WriteLine(bytesRead);
        //    }
        //}



    }

}
